const canvas = document.getElementById('webgl')
const gl = getWebGLContext(canvas)
const modeList = [
    gl.POINTS,
    gl.LINES,
    gl.LINE_STRIP,
    gl.LINE_LOOP,
    gl.TRIANGLES,
    gl.TRIANGLE_STRIP,
    gl.TRIANGLE_FAN]
const strList = [
    'POINTS',
    'LINES',
    'LINE_STRIP',
    'LINE_LOOP',
    'TRIANGLES',
    'TRIANGLE_STRIP',
    'TRIANGLE_FAN'
]
//此例 添加对片元着色器的第一次尝试 改变颜色

let VertexShaderSource =
    'attribute vec4 a_Position;\n' +
    'void main(){ \n' +
    '   gl_Position = a_Position;\n' +
    '   gl_PointSize = 10.0;\n' +
    '}\n'
let FragmentShaderSource =
    'precision mediump float;\n' +
    'uniform vec4 u_FragColor;\n' +
    'void main(){\n' +
    '    gl_FragColor = u_FragColor;\n' +
    '}\n'

function main() {
    initShaders(gl, VertexShaderSource, FragmentShaderSource)

    //新内容: 设置顶点位置
    let n = initVertexBuffers(gl, true, false)
    if (n < 0) {
        console.log('Failed to set the position of the vertices');
        return
    }

    let index = 0
    main.prototype.timer = setInterval(() => {
        if (index < modeList.length) {
            //设置背景色
            gl.clearColor(0.5, 0.5, 0.5, 1)
            //清一下
            gl.clear(gl.COLOR_BUFFER_BIT)

            gl.drawArrays(modeList[index], 0, n)
            index++;
            return
        }
        index = 0
    }, 1 * 1000)
}
let flourCount = 0
function onClick() {
    if (flourCount == modeList.length) {
        flourCount = 0
    }
    clearInterval(main.prototype.timer)
    initVertexBuffers(gl, false, true)
    gl.clearColor(0.5, 0.5, 0.5, 1)
    gl.clear(gl.COLOR_BUFFER_BIT)
    document.getElementById('doc_Name').innerHTML = strList[flourCount]
    gl.drawArrays(modeList[flourCount], 0, 4)
    flourCount++
}

function initVertexBuffers(gl, triangle, rect) {
    let vertices = undefined
    let n = undefined
    if (triangle) {
        //顶点的顺序也至关重要
        vertices = new Float32Array([
            0.0, 0.5,
            -0.5, -0.5,
            0.5, -0.5
        ])
        n = 3
    } else if (rect) {
        vertices = new Float32Array([
            //顶点的顺序也至关重要
            -0.5, 0.5,
            -0.5, -0.5,
            0.5, 0.5,
            0.5, -0.5
        ])
        n = 4
    }

    //创建缓冲区对象------新玩意：对象
    let vertexBuffer = gl.createBuffer()
    if (!vertexBuffer) {
        console.log('Failed to create the buffer object');
        return -1
    }

    //将缓冲区对象绑定到目标
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer)

    //向缓冲区对象写入数据
    gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW)



    let a_Position = gl.getAttribLocation(gl.program, 'a_Position')

    //将缓冲区对象分配给a_Position变量
    gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0)

    //连接a_Position变量与分配给它的缓冲区对象
    gl.enableVertexAttribArray(a_Position)

    return n
}